<script setup>
import {
  settleRate,
  myBankcard,
  customermyBalance,
  applyBrokerage,
  computeBrokerage,
  getAuthApi,
} from "@/services/reward";
import { nextTick, ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import moneyurl from "@/pages/servicereward/static/reward/moey.png";
import {
  earnCount,
  mine,
  isPayPassApi,
  checkPayPass,
  userinfo,
} from "@/services/user";

const popup = ref(null);
const selectcardindex = ref(0);
const cardlist = ref([
  // {
  //   account_type: 1,
  //   bank_name: "通用余额",
  //   bank_number: "（默认）",
  //   bank_logo: moneyurl,
  // },
]);

const settleRatedata = ref({});

onShow(async () => {
  cardlist.value = [
    // {
    //   account_type: 1,
    //   bank_name: "微信",
    //   bank_number: "默认",
    //   bank_logo: moneyurl,
    // },
  ];
  await getmyBankcard();
  await minefun();
  await userinfoFun();
  await getAuthFun();
  if (settleRatedata.value.is_real_name == "1" && !userinfoData.value.is_auth) {
    showDelete.value = true;
    return;
  }
});

const authObj = ref({});
async function getAuthFun() {
  let res = await getAuthApi();
  if (res.code == 200) {
    authObj.value = res.data;
  } else {
    uni.showToast({
      title: res.info,
      icon: "none",
    });
  }
}

settleRatefun();

async function settleRatefun() {
  let res = await settleRate();
  if (res.code == 200) {
    settleRatedata.value = res.data;
  } else {
    uni.showToast({
      title: res.info,
      icon: "none",
    });
  }
}
async function getmyBankcard() {
  let res = await myBankcard();
  cardlist.value = [...cardlist.value, ...res.data.list];
}
const num = ref("");
const jsnum = ref(0);
const balancenum = ref(0);
const isinputto = ref(false);
const isshowput = ref(true);
const pay_pass = ref("");

const showPassword = ref(false);

const numinputfun = (val) => {
  nextTick(() => {
    num.value = validateCurrency(num.value);
  });
};

async function isPayPassApifun() {
  return await isPayPassApi();
}

function validateCurrency(value) {
  // 移除所有非数字和小数点字符
  const sanitizedValue = value.replace(/[^0-9.]/g, "");
  // 匹配2个小数点以及之后的数字(如果有)
  const match = sanitizedValue.match(/^(\d+(\.\d{0,2})?)/);
  // 如果没有匹配到，则返回null
  if (!match) return null;
  // 返回格式化后的金额字符串

  return match[0];
}

const maskClick = () => {
  popup.value.close();
};
const numblur = () => {
  getcomputeBrokerage(Number(num.value));
};

async function getcomputeBrokerage(num1) {
  try {
    let res = await computeBrokerage({
      price: num1,
    });
    if (res.code == 200) {
      jsnum.value = res.data.actual_price;
    } else {
    }
  } catch (ref) {
    uni.showToast({
      title: ref.info,
      icon: "none",
    });
    let serviceab = settleRatedata.value.brokerage_service_rate / 100;
    let tax = settleRatedata.value.brokerage_tax_rate / 100;
    let fwnum = Number(num.value) * serviceab;
    let serve = Number(num.value) * tax;
    let toall = serve + fwnum;

    jsnum.value = roundToTwo(Number(num.value) - toall);
  }
}

function roundToTwo(num) {
  return Math.round(num * 100) / 100;
}
const minefun = async () => {
  try {
    let res = await mine();
    balancenum.value = res.data.balance;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const getcodes = async () => {
  num.value = String(balancenum.value);
  getcomputeBrokerage(Number(num.value));

  numblur();
};

const selectidcard = () => {
  popup.value.open();
};

const selectcardindexfun = (item, index) => {
  selectcardindex.value = index;
  popup.value.close();
};

const applyBrokeragefun = async () => {
  if (cardlist.value.length <= 0 || !cardlist.value[selectcardindex.value].id) {
    uni.showToast({
      title: "请绑定银行卡",
      icon: "none",
    });
    return;
  }

  if (Number(num.value) <= 0) {
    uni.showToast({
      title: "提现金额不能为0,请重新输入!",
      icon: "none",
    });
    return;
  }
  if (Number(num.value) > balancenum.value) {
    uni.showToast({
      title: "金额大于可提现金额!",
      icon: "none",
    });
    return;
  }

  if (Number(num.value) < settleRatedata.value.brokerage_min_price) {
    uni.showToast({
      title: `单次最低提现金额为${settleRatedata.value.brokerage_min_price}元!`,
      icon: "none",
    });
    return;
  }

  if (Number(num.value) > settleRatedata.value.brokerage_max_price) {
    uni.showToast({
      title: `单次最高提现金额为${settleRatedata.value.brokerage_max_price}元!`,
      icon: "none",
    });
    return;
  }

  if (authObj.value && authObj.value.status == 0) {
    uni.showToast({
      title: "正在实名认证中，请耐心等待！",
      icon: "none",
    });
    return;
  }

  if (settleRatedata.value.is_real_name == "1" && !userinfoData.value.is_auth) {
    showDelete.value = true;
    return;
  }
  if (authObj.value && authObj.value.status == -3) {
    uni.showToast({
      title: `实名认证未通过,${authObj.value.fail_message}请重新提交!`,
      icon: "none",
    });
    return;
  }

  try {
    let res = await isPayPassApifun();
    if (res.code == 200 && res.data == 0) {
      uni.showToast({
        title: "没有支付密码，前往设置",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/mysetting/modify/index?isshowPassword=" + 0,
        });
      }, 500);
      return;
    } else {
      showPassword.value = true;
      pay_pass.value = "";
      setTimeout(() => {
        focusinput.value = true;
      }, 500);
    }
  } catch (e) {}
};

const paymentfun = async () => {
  let datas = {};
  if (
    cardlist.value &&
    cardlist.value[selectcardindex.value].account_type == 1
  ) {
    datas = {
      account_type: 1,
      price: num.value,
      pay_pass: pay_pass.value,
    };
  } else {
    datas = {
      account_type: 1,
      price: num.value,
      bank_id: cardlist.value && cardlist.value[selectcardindex.value].id,
      pay_pass: pay_pass.value,
    };
  }

  try {
    let res = await applyBrokerage(datas);
    if (res.code === 200) {
      uni.redirectTo({
        url: "/pages/servicereward/myreward/rewardpay",
      });
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const addcardfun = () => {
  popup.value.close();
  if (authObj.value && authObj.value.status == 0) {
    uni.showToast({
      title: "正在实名认证中，请耐心等待！",
      icon: "none",
    });
    return;
  }
  if (settleRatedata.value.is_real_name == "1" && !userinfoData.value.is_auth) {
    showDelete.value = true;
    return;
  }

  if (authObj.value && authObj.value.status == -3) {
    uni.showToast({
      title: `实名认证未通过,${authObj.value.fail_message}请重新提交!`,
      icon: "none",
    });
    return;
  }
  uni.navigateTo({
    url: "/pages/servicereward/myreward/addBankCard",
  });
};

const keyWord = ref(null);

//金额键盘
const inp = (e) => {};

const hide = () => {
  if (num.value > 0) {
    numblur();
  } else {
    jsnum.value = 0;
  }
  isinputto.value = false;
  isshowput.value = true;
};
const confirm = () => {
  getcomputeBrokerage(Number(num.value));
  nextTick(() => {
    keyWord.value.close();
    isshowput.value = true;
  });
};
const clearnumfun = () => {
  isinputto.value = true;
  num.value = "";
};
const showinputkd = () => {
  isinputto.value = true;
  isshowput.value = false;
  keyWord.value.open();
};

// 定义 finish 方法
const finish = async (e) => {
  pay_pass.value = e;
  try {
    let res = await checkPayPass({ pay_pass: pay_pass.value });
    if (res.code == 200) {
      paymentfun();
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    pay_pass.value = "";
  }
};

const forgot = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index?isshowPassword=" + 1,
  });
};

const focusinput = ref(false);
const close = () => {
  showPassword.value = false;
  focusinput.value = false;
  pay_pass.value = "";
};

//用户信息
const userinfoData = ref({});
const userinfoFun = async () => {
  try {
    let res = await userinfo();
    if (res.code == 200) {
      userinfoData.value = res.data;
    } else {
      uni.showToast({
        title: res.info,
        icon: "none",
      });
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

//认证
const showDelete = ref(false);
const closeDelete = () => {
  showDelete.value = false;
};
const addressDelete = () => {
  showDelete.value = false;
  uni.navigateTo({
    url: "/pages/servicereward/myreward/realname",
  });
};

const gosubmit = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/realname",
  });
};
</script>

<template>
  <jia-PayKeyboard
    :confirmStyle="{ backgroundColor: '#F3498B ' }"
    class="keyWord-index"
    :overlayClose="true"
    ref="keyWord"
    v-model="num"
    @input="inp"
    @confirm="confirm"
    @hide="hide"
  ></jia-PayKeyboard>
  <view class="balance">
    <view
      class="balance-notice"
      @click="gosubmit"
      v-if="authObj && authObj.status == -3"
    >
      <view class="balance-notice-left">
        <text
          >您提交的实名认证信息：{{ authObj && authObj.fail_message }}无法签约
        </text>
      </view>

      <view class="balance-notice-right">
        <text>重新提交</text>
        <uni-icons
          type="right"
          size="12"
          color="#8C8C8C"
          class="sala-det-more-right"
        ></uni-icons>
      </view>
    </view>
    <view
      class="balance-notice balance-notice1"
      v-if="authObj && authObj.status == 0"
    >
      您提交的实名认证信息：正在审核中,请耐心等待!
    </view>
    <view class="balance-k">
      <view
        class="balance-k-title"
        @click="selectidcard"
        v-if="cardlist.length > 0"
      >
        <view class="balance-k-title-left">
          <!-- {{cardlist[selectcardindex].bank_logo}} -->
          <image
            :src="
              cardlist[selectcardindex].bank_logo
                ? cardlist[selectcardindex].bank_logo
                : cardlist[0].bank_logo
            "
            mode="widthFix"
          >
          </image>
          <text
            >{{ cardlist[selectcardindex].bank_name }}({{
              cardlist[selectcardindex].bank_number
            }})
          </text>
        </view>

        <view class="balance-k-title-right">
          <uni-icons
            type="right"
            size="18"
            color="#8C8C8C"
            class="sala-det-more-right"
          ></uni-icons>
        </view>
      </view>

      <view
        class="balance-k-title"
        @click="selectidcard"
        v-if="cardlist.length <= 0"
      >
        <view class="balance-k-title-left">
          <text style="margin-left: 0;">去绑定银行卡 </text>
        </view>

        <view class="balance-k-title-right">
          <uni-icons
            type="right"
            size="18"
            color="#8C8C8C"
            class="sala-det-more-right"
          ></uni-icons>
        </view>
      </view>

      <view class="balance-k-js">
        <view class="balance-k-info">
          <uni-forms :modelValue="formData" label-width="60">
            <view class="paynum-title">
              提现{{ selectbtlistindex === 3 ? "积分" : "金额" }}
            </view>
            <!-- <view class="paynum-index">
							<view class="">s
								
							</view>
							</view> -->
            <view class="input-k-sr">
              <view class="item-left">
                <view class="item-dw"> ￥ </view>
                <view
                  class="item-sr"
                  :class="num || isinputto ? 'item-sr-color' : ''"
                  @click.stop="showinputkd"
                >
                  <view class="item-sr-num">
                    <text>{{ num || isinputto ? num : "请输入" }}</text>

                    <view v-if="isinputto" class="item-sr-num-right"> </view>
                  </view>

                  <uni-icons
                    @click="clearnumfun"
                    v-if="num && isinputto"
                    class="uni-icons-cloes-to"
                    type="clear"
                    size="30"
                  ></uni-icons>
                </view>
              </view>

              <view class="getcodes">
                <text>元</text>
              </view>
            </view>

            <!-- <uni-forms-item label="￥" name="pay_price" class="forms-item-k num-pay">
                          
                            <uni-easyinput type="digit" v-model="num" @focus="focusfun" placeholder="请输入" @input="numinputfun" @blur="numblur">
                                <template #right>
                                    <view class="getcodes" @click="getcodes">
                                        <text class="getcodes-moery">全部转出</text>
                                        <text>元</text>
                                    </view>
                                </template>
                            </uni-easyinput>
                        </uni-forms-item> -->
            <view class="paynum-hx"> </view>
          </uni-forms>
        </view>
      </view>

      <view class="balance-k-js-hx"> </view>
      <view class="num-pay-num">
        <text>余额 : {{ balancenum }}元</text>
        <text @click="getcodes" class="getcodes-moery">全部转出</text>
      </view>
    </view>
    <view class="balance-k-ruls">
      <view class="balance-k-yuan"> </view>
      <view class="balance-k-info-num"> 实际到账：{{ jsnum }} 元 </view>
      <view class="balance-k-info-sm">
        平台收取{{ settleRatedata.brokerage_service_rate }}%的平台服务费+{{
          settleRatedata.brokerage_tax_rate
        }}%的代扣代缴税费
      </view>
    </view>

    <view class="foods" v-if="!isinputto">
      <view class="bt-foods" @click="applyBrokeragefun"> 结算 </view>
    </view>
  </view>

  <uni-popup ref="popup" type="bottom" @maskClick="maskClick">
    <view class="popup-bt">
      <view class="popup-select-title"> 选择银行卡 </view>
      <view class="popup-select-list">
        <view
          class="popup-item"
          v-for="(item, index) in cardlist"
          :key="index"
          @click="selectcardindexfun(item, index)"
        >
          <view class="popup-item-name">
            <image
              :src="
                item.bank_logo
                  ? item.bank_logo
                  : '@/pages/servicereward/static/reward/moey.png'
              "
              mode="widthFix"
            >
            </image>
            <text>{{ item.bank_name }}({{ item.bank_number }})</text>
          </view>
          <view class="popup-item-icon" v-if="selectcardindex == index">
            <image
              src="@/static/cloudlibrary/select.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
        <!-- <view class="popup-item">
					<view class="popup-item-name">
						通用金额
					</view>
					<view class="popup-item-icon">
						<image src="../../static/reward/select-d.png" mode="widthFix"></image>
					</view>
				</view> -->

        <view class="popup-bt-add" @click="addcardfun">
          <text class="popup-bt-add-j">+</text> <text>添加储蓄卡提现</text>
        </view>
      </view>
    </view>
  </uni-popup>

  <!-- 密码弹框 -->
  <view class="password_show">
    <u-popup
      :show="showPassword"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="password">
        <view class="popup-content-title">支付密码</view>
        <u-code-input
          v-model="pay_pass"
          :maxlength="6"
          dot
          size="80"
          @change="onChange"
          @finish="finish"
          :focus="focusinput"
        ></u-code-input>
        <view class="footer">
          <view class="closefun" @click="showPassword = false">取消</view>
          <view class="forgot" @click="forgot">忘记密码？</view>
        </view>
      </view>
    </u-popup>
  </view>

  <!-- 实名认证弹框 -->
  <view class="password_show">
    <u-popup
      :show="showDelete"
      mode="center"
      round="10"
      @close="close"
      @open="open"
    >
      <view class="productGift">
        <view class="popup-content-title">实名认证</view>
        <view class="popup-content-item"
          >提现结算由第三方财务管理平台进行结算与发放，需收集您的实名信息用于身份验证、税务申报
          等用途。</view
        >
        <view class="popup-content-box">
          <view class="popup-content-bt">
            <view class="popup-content-qx" @click="closeDelete">取消</view>
            <view class="popup-content-cl" @click="addressDelete">去认证</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "balance.scss";
</style>
